<script setup lang="ts">
import { ModalUtil } from '/@lib/utils/modal.ts'
import { useModalStatus } from '/@lib/hooks/useModalStatus.ts'
import { useForm } from '/@lib/hooks/useForm.ts'
import { useLoading } from '/@lib/hooks/useLoading.ts'
import { RoleVO } from '/@/api/system/sysRole/types'
import { ApiSysRole } from '/@/api/system/sysRole'

const { loading, showLoading, hideLoading } = useLoading()
const { modalVisible, modalTitle, showModal, hideModal, setModalTitle } = useModalStatus()
const formRef = ref()
const { form, resetForm } = useForm({
  roleId: undefined,
  sortNum: 1,
  status: '0',
  roleName: '',
  roleKey: '',
  deptCheckStrictly: true,
  dataScope: '1',
  deptIds: []
})
const closeCancel = () => {
  treeRef.value?.setCheckedKeys([])
  isExpandAll.value = true
  isCheckAll.value = false
  resetForm()
  hideModal()
}
const openRow = ref<any>()
/** 打开 Modal 操作 */
const open = async (row: RoleVO) => {
  showModal()
  setModalTitle(`分配数据权限`)
  Object.assign(form, row)
  await handleOpenDefaultData(row)
}
defineExpose({ open })
const emit = defineEmits(['submit-success'])
/** Modal Open 处理默认数据 */
const handleOpenDefaultData = async (row: RoleVO) => {
  openRow.value = {
    roleId: row.roleId,
    roleName: row.roleName,
    roleKey: row.roleKey
  }
  await getTreeList()
}
/** 提交按钮 */
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    showLoading()
    if (form.roleId) {
      form.deptIds = getTreeAllCheckedKeys()
      await ApiSysRole.authDataScope(form)
    }
    ModalUtil.msgSuccess('操作成功')
    emit('submit-success')
    hideModal()
  } finally {
    hideLoading()
  }
}

/** 树区域 */
const isExpandAll = ref(true)
const isCheckAll = ref(false)
const treeRef = ref()
const treeData = ref<any[]>([])

const getTreeList = async () => {
  showLoading()
  try {
    const res = await ApiSysRole.deptTreeChecked(openRow.value.roleId)
    treeData.value = res.treeList
    await nextTick(() => {
      treeRef.value?.setCheckedKeys(res.checkedKeys)
    })
  } finally {
    hideLoading()
  }
}
/** 树权限（展开/折叠）*/
const handleCheckedTreeExpand = (value: boolean) => {
  let _treeList = treeData.value
  for (let i = 0; i < _treeList.length; i++) {
    if (treeRef.value) {
      treeRef.value.store.nodesMap[_treeList[i].id].expanded = value
    }
  }
}
/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value: any) => {
  treeRef.value?.setCheckedNodes(value ? (treeData.value as any) : [])
}
/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value: any) => {
  form.deptCheckStrictly = value
}
/** 所有树节点数据 */
const getTreeAllCheckedKeys = (): any => {
  // 目前被选中的部门节点
  let checkedKeys = treeRef.value?.getCheckedKeys()
  // 半选中的部门节点
  let halfCheckedKeys = treeRef.value?.getHalfCheckedKeys()
  if (halfCheckedKeys) {
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys)
  }
  return checkedKeys
}

/** 选择角色权限范围触发 */
const dataScopeSelectChange = async (value: string) => {
  if (value !== '2') {
    treeRef.value?.setCheckedKeys([])
  }
}

/** 数据范围选项 */
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' }
])

const formItems = ref([
  {
    prop: 'roleName',
    label: '角色名称',
    attrs: {
      disabled: true
    }
  },
  {
    prop: 'roleKey',
    label: '权限字符',
    attrs: {
      disabled: true
    }
  },
  {
    prop: 'dataScope',
    label: '权限范围',
    slot: 'agel-radio',
    attrs: {
      border: true,
      options: dataScopeOptions,
      onChange: dataScopeSelectChange
    }
  },
  {
    label: '自定义数据权限',
    slot: 'slot-authDataScope',
    hidden: computed(() => form.dataScope !== '2'),
    attrs: {
      disabled: true
    }
  }
])
</script>

<template>
  <el-dialog
    :title="modalTitle"
    v-model="modalVisible"
    width="50%"
    top="5vh"
    @close="closeCancel"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" v-loading="loading" :model="form" label-width="180px" label-position="right">
      <AgelFormDesc :items="formItems" border :column="1">
        <template #slot-authDataScope>
          <el-checkbox border v-model="isExpandAll" @change="(value: any) => handleCheckedTreeExpand(value)">
            展开/折叠
          </el-checkbox>
          <el-checkbox border v-model="isCheckAll" @change="(value: any) => handleCheckedTreeNodeAll(value)">
            全选/全不选
          </el-checkbox>
          <el-checkbox
            border
            v-model="form.deptCheckStrictly"
            @change="(value: any) => handleCheckedTreeConnect(value)"
          >
            父子联动
          </el-checkbox>
          <el-tree
            class="border"
            style="height: 300px; overflow: auto"
            ref="treeRef"
            node-key="id"
            :data="treeData"
            :props="{ label: 'label', children: 'children' }"
            show-checkbox
            default-expand-all
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
          >
          </el-tree>
        </template>
      </AgelFormDesc>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <div>
        <el-button @click="closeCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-radio) {
  margin-top: calc(var(--el-margin) / 2);
  margin-bottom: calc(var(--el-margin) / 2);

  //.el-radio + .el-radio {
  //  margin-bottom: var(--el-margin);
  //}
}

:deep(.el-tree) {
  margin-top: var(--el-margin);
  padding-bottom: var(--el-margin);
  //margin-bottom: var(--el-margin);
}
</style>
